package com.sweet.pay.dto;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.wxpay.sdk.IWXPayDomain;
import com.github.wxpay.sdk.WXPayConfig;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * Created by sweet on 2019/6/5.
 * ---------------------------
 */
public class WxConfig extends WXPayConfig {

  private final JSONObject jsonObject;


  public WxConfig(String appId,
                  String mchId,
                  String key,
                  String certPath) {
    final JSONObject jsonObject = new JSONObject();
    jsonObject.put("appId", appId.trim());
    jsonObject.put("mchId", mchId.trim());
    jsonObject.put("key", key.trim());
    jsonObject.put("certPath", certPath.trim());
    this.jsonObject = jsonObject;
  }


  @Override
  public String getAppID() {
    return jsonObject.getString("appId");
  }

  @Override
  public String getMchID() {
    return jsonObject.getString("mchId");
  }

  @Override
  public String getKey() {
    return jsonObject.getString("key");
  }

  @Override
  public InputStream getCertStream() {
    String cert = jsonObject.getString("certPath");
    byte[] bytes = new byte[0];
    try {
      bytes = Files.readAllBytes(Paths.get(cert));
    } catch (IOException e) {
      e.printStackTrace();
      throw new RuntimeException(e.getMessage());
    }
    return new ByteArrayInputStream(bytes);
  }

  @Override
  public IWXPayDomain getWXPayDomain() {
    return new IWXPayDomain() {
      @Override
      public void report(String domain, long elapsedTimeMillis, Exception ex) {

      }

      @Override
      public DomainInfo getDomain(WXPayConfig config) {
        return new DomainInfo("api.mch.weixin.qq.com", true);
      }
    };
  }

  @Override
  public int getHttpConnectTimeoutMs() {
    return 6000;
  }

  @Override
  public int getHttpReadTimeoutMs() {
    return 8000;
  }

  @Override
  public boolean shouldAutoReport() {
    return true;
  }

  @Override
  public int getReportWorkerNum() {
    return 6;
  }

  @Override
  public int getReportQueueMaxSize() {
    return 10000;
  }

  @Override
  public int getReportBatchSize() {
    return 10;
  }
}